﻿using System;
using System.Collections.Generic;
using System.Linq;
using ExtendedMvc.Common.Diagnostics;
using ExtendedMvc.Common.EntityFramework;

namespace ExtendedMvc.WebTest.Model {
	public class BaseRepository<TEntity> : IBaseRepository<TEntity>
		where TEntity : class, IBaseEntity {

		protected List<TEntity> Source { get; private set; }

		public BaseRepository() {
			Source = new List<TEntity>();
		}

		public virtual IEnumerable<TEntity> All() {
			return Source;
		}

		public virtual bool Exists(long id) {
			Check.Argument.IsNotNegative(id, "id");

			return All().Any(entity => entity.Id == id);
		}

		public virtual TEntity GetById(long id) {
			Check.Argument.IsNotNegative(id, "id");

			return All().SingleOrDefault(entity => entity.Id == id);
		}

		public virtual IEnumerable<TEntity> Filter(Func<TEntity, bool> predicate) {
			Check.Argument.IsNotNull(predicate, "predicate");

			return All().Where(predicate);
		}

		public virtual long Count(Func<TEntity, bool> predicate = null) {
			if (predicate == null) return All().Count();
			return All().Count(predicate);
		}

		public virtual void Add(TEntity entity) {
			Check.Argument.IsNotNull(entity, "entity");

			Source.Add(entity);
			entity.Id = Source.LastIndexOf(entity) + 1;
		}

		public virtual void Delete(TEntity entity) {
			Check.Argument.IsNotNull(entity, "entity");

			Source.Remove(entity);
		}

		public virtual void Save() {
			//Does Nothing
		}

		public virtual void Clear() {
			Source.Clear();
		}
	}
}
